<template>
	<view @touchstart="touchStart" @touchend="touchEnd">
	    <!-- 头部组件 -->
	    <navbar ref="navbar" ></navbar>
		
		<!-- table导航条 -->
		<view  style=" height: 40px; " class="tabs">
		
		<view class="u_tabs">
			<u-tabs :list="list1" :scrollable="false" @click="tabClick"
			 lineColor="#ffff"
			    :inactiveStyle="{
			         color: '#efefef',
			        'font-size':'14px' ,
			    }"
				:activeStyle="{
				    color: '#ffffff',
				    fontWeight: 'bold',
				    'font-size':'14px' ,
				}"
			>
				<view slot="right" style="padding-left: 4px;"  @tap="map()">
				    <view class="mapBox">
						<view class="mapBoxleft">
						</view>
				    	<view class="">
				    		<u-button  color="#000000" type="primary" icon="map" iconColor="#ffd34d" shape="circle" text="路线" size="mini"></u-button>
				    	</view>
				    </view>
				</view>
			</u-tabs>
		</view>	
		</view>
		
	    <!-- 内容 -->
		<view v-if="hasLogin">
			<view class="contents" >
				<view v-if="tabsIndex==0">
					<newTask ref="newTask"></newTask>
				</view>
				<view v-if="tabsIndex==1">
					<waitService ref="waitService"></waitService>
				</view>
				<view v-if="tabsIndex==2">
					<inService ref="inService"></inService>
				</view>
				<view v-if="tabsIndex==3">
					<completeService ref="completeService"></completeService>
				</view>
			</view>
			
			<!-- 底部 -->
			<u-tabbar	:fixed="true"	:placeholder="true"	:safeAreaInsetBottom="true"	>
				<view style="float: left; margin-top: 5px;"  >
				</view>
					<!-- <u-tabbar-item text="接单设置" icon="setting"@click="navigateTo(receivingSettings)" ></u-tabbar-item> -->
					<u-button  :plain="true" shape="circle" :loading="loadingTabbar" size="small" text="刷新列表"
					icon="reload"  style="width:760rpx; margin: 10px; margin-right: 10px;" @click="refresh"></u-button>
					<!-- <u-button v-if="userInfo.isOnline==false" @click="isOnlineClick()" :plain="true" shape="circle" :loading="loadingTabbar" size="small" text="点击上线"
					style="width:760rpx; margin: 10px; margin-right: 10px;"></u-button> -->
					
			</u-tabbar>
			
			<!-- <左边侧滑 -->
			<u-popup :show="show"  mode="left"   @close="show=false">
				<view style="background-color: #f3f3f3;">
					<myindex @Logout="toLogout" ref="myindex"></myindex>
				</view>
			</u-popup>
		</view>
		<!-- 未登录显示 -->
		<view v-else @click="navToLogin" >
			<u-empty  mode="permission"textColor="#f00000"     text="请先登录>"   >
			</u-empty>
		</view>
	</view>
</template>

<script>
	const myPlugin = requirePlugin('WechatSI');
	//import WebsocketTask from '../../Utils/websocket.js'
	import {
		mapState
	} from 'vuex';  
	import {
	    mapMutations  
	} from 'vuex';
	import uRow from "@/pagesB/uview-ui/components/u-row/u-row";
	import uCol from "@/pagesB/uview-ui/components/u-col/u-col";
	import uDivider from "@/pagesB/uview-ui/components/u-steps/u-steps";
	import uSteps from "@/pagesB/uview-ui/components/u-steps/u-steps";
	import uStepsItem from "@/pagesB/uview-ui/components/u-steps-item/u-steps-item";
	import uButton from "@/pagesB/uview-ui/components/u-button/u-button";
	import uPopup from "@/pagesB/uview-ui/components/u-popup/u-popup";
	import uLoadmore from "@/pagesB/uview-ui/components/u-loadmore/u-loadmore";
	import uEmpty from "@/pagesB/uview-ui/components/u-empty/u-empty";
	import uTabs from "@/pagesB/uview-ui/components/u-tabs/u-tabs";
	import uTabbar from "@/pagesB/uview-ui/components/u-tabbar/u-tabbar";
	import uNavbar from "@/pagesB/uview-ui/components/u-navbar/u-navbar";
	import uIcon from "@/pagesB/uview-ui/components/u-icon/u-icon";
	import uBadge from "@/pagesB/uview-ui/components/u-badge/u-badge";
	import uCellGroup from "@/pagesB/uview-ui/components/u-cell-group/u-cell-group";
	import uCell from "@/pagesB/uview-ui/components/u-cell/u-cell";
	
	import myindex from "../my/myindex.vue";
	import navbar from "./navbar.vue";
	import newTask from "./serviceList/newTask.vue";
	import waitService from "./serviceList/waitService.vue";
	import inService from "./serviceList/inService.vue";
	import completeService from "./serviceList/completeService.vue";
	export default {
		components:{   
			navbar,newTask,waitService,inService,myindex,completeService,
			uRow,uCol,uDivider,uSteps,uStepsItem,uButton,uLoadmore,uPopup,uEmpty,uTabs,uTabbar,uNavbar,uIcon,uBadge,uCellGroup,uCell,
		}, 
		data() {
			return {
				show:false,
				startX: 0, //滑动开始x轴位置
				vwidth: 0, //滑动的x轴距离
				loadingTabbar:false,
				value7:1,
				tabsIndex:0,
				
				routeMap:'/pagesB/index/routeMap',//路线地图
				receivingSettings:'/pagesB/index/receivingSettings',//接单设置
				swiperList: [
		                    'https://cdn.uviewui.com/uview/swiper/swiper1.png',
		                    'https://cdn.uviewui.com/uview/swiper/swiper2.png',
		                    'https://cdn.uviewui.com/uview/swiper/swiper3.png',
		                ],
				list1: [{
				        name: '新任务',
				    }, {
				        name: '待服务',
						
				    }, {
				        name: '服务中'
				    }, {
				        name: '已完成'
				   }],
				datas:{
					phone:"17687214131",
					password:"123",
					name:"黄师傅",
					isOnline:false,
					isDispatch:false,
					name:"",
					type:"",
				}   
			}
		},
		onShow() {
			wx.hideTabBar()
			uni.stopPullDownRefresh();
			//this.$refs.navbar.showPage(false);
			this.refresh();
			this.connectSocket();
		},
		mounted() {
			//获取当前位置 需用户授权
			//this.getCurrentLocal()
			//this.julijiusan();
			//this.showPage(true)
			//this.$refs.navbar.showPage(false);
			
		},
		computed:{
			//获取是否登录
			...mapState(['hasLogin','userInfo']) 
		},
	    
		methods: {
			...mapMutations(['login']),
			
			//退出登录
			toLogout(edn){
				console.log("	//登录信息",edn)
				//this.show=false
			},
			//点击上线
			isOnlineClick(){
				/* uni.getStorage({
					key: 'LoginTK',
					success: (res) => {
						res.data.isOnline=true
						//更新登录信息
						this.login(res.data);
						//console.log("	//登录信息",JSON.stringify(res.data))
					}
				}) */
			},
			//table导航条切换
			tabClick(item){
				if(!this.userInfo.id){
					this.utils.notLogin()
					return
				}
				this.tabsIndex=item.index
				//console.log(item)
			},
			//页面跳转方法
            navigateTo(urls) {
            	uni.navigateTo({
            	   url: urls
            	});
            },
			//跳转登录页面
			navToLogin(){
				uni.navigateTo({
					url: '/pages/login/login'
				})
			},
			//底部切换
			clickTabbar(itme){
				alert(JSON.stringify(itme))
			},
			//左右侧滑
			touchStart(e) {
				if (e.touches.length == 1) {
					this.startX = e.touches[0].clientX;
				}
			},
			//上拉事件触发
			onReachBottom(){
				if(this.tabsIndex==0)this.$refs.newTask.onReachBottomZ();
				if(this.tabsIndex==1)this.$refs.waitService.onReachBottomZ();
				if(this.tabsIndex==2)this.$refs.inService.onReachBottomZ();
				if(this.tabsIndex==3)this.$refs.completeService.onReachBottomZ();
			},
			//下拉触发
			onPullDownRefresh() {
				if(this.tabsIndex==0)this.$refs.newTask.onPullDownRefreshZ();
				if(this.tabsIndex==1)this.$refs.waitService.onPullDownRefreshZ();
				if(this.tabsIndex==2)this.$refs.inService.onPullDownRefreshZ();
				if(this.tabsIndex==3)this.$refs.completeService.onPullDownRefreshZ();
				this.$refs.navbar.showPage(false);
				setTimeout(() => {
					// 操作完成时，必须结束下拉刷新，否则一直会有 loading 标志
					uni.stopPullDownRefresh();
				}, 1000);
				
			},
			touchEnd(e) {
				if (e.changedTouches.length == 1) {
					var endX = e.changedTouches[0].clientX;
					let diff = endX - this.startX;
					const that = this
					if (Math.abs(diff) > 100) {
						console.log(diff)
						if (diff > 0) { //右滑 这里可以放需要进行的业务逻辑 
							this.show=true
							this.$refs.myindex.showPage();
						} else { //左滑	这里可以放需要进行的业务逻辑
							this.show=false
						}
					} 
				}
			},
			//刷新列表
			refresh(){
				if(this.tabsIndex==0)this.$refs.newTask.onPullDownRefreshZ();
				if(this.tabsIndex==1)this.$refs.waitService.onPullDownRefreshZ();
				if(this.tabsIndex==2)this.$refs.inService.onPullDownRefreshZ();
				if(this.tabsIndex==3)this.$refs.completeService.onPullDownRefreshZ();
				this.$refs.navbar.showPage(false);
			},
			//返回刷新
			reload(){
				console.log("返回刷新")
				this.tabsIndex=2
				this.$refs.inService.reload();
			},
			map(){
				if(!this.userInfo.id){
					this.utils.notLogin()
					return
				}
				uni.navigateTo({
					url: '/pagesB/index/routeMap'
				})
			},
			connectSocket() {
				let that = this;
				let userInfo = uni.getStorageSync('userInfo');
				//console.log('调用连接websocket',userInfo.id)
				uni.closeSocket()
				if(!userInfo.id) return;
				/* let websocket = new WebsocketTask(this.http.httpsLian.WebSocketConnect+ "?userId=" + userInfo.id,5000)
				console.log("websocket",websocket) */
				this.socketTask = uni.connectSocket({
						url: this.http.httpsLian.WebSocketConnect+ "?userId=" + userInfo.id,
						success(res) {
							console.log("websocket连接成功");
							// that.isSuccess = true
						},
						fail(err) {
							console.log("报错", err);
						}
					},
				);
				this.socketTask.onOpen(function(res) {
					console.log('WebSocket连接已打开！');
					that.isSuccess = true
					//that.heart()
				})
				
				this.socketTask.onMessage(function(res) {
					console.log('收到服务器内容：' + res.data);
					if(res.data=="接收内容：连接成功" ) return;
					if( res.data=="接收内容：连接失败") return;
					that.getnavbar()
					that.dispatch(res.data);
					//that.handlerMsg(JSON.parse(res.data)) //这里是对获取到的数据进行操作
				});
			 
			 
				this.socketTask.onError(function(res) {
					console.log('WebSocket连接打开失败，请检查！');
					console.log(res);
					//进入重新连接
					that.reconnect();
			 
				})
				// // 监听连接关闭 -
				this.socketTask.onClose((e) => {
					console.log('WebSocket连接关闭！');
					clearInterval(that.timer)
					that.timer = ''
					if (!that.isClose) {
						that.reconnect()
					}
				})
				console.log(this.socketTask)
			},
			//进入重新连接
			reconnect() {
				console.log('进入断线重连');
				// this.socketTask.close();
				this.socketTask = null;
				setTimeout(() => {
					this.connectSocket()
				}, 300000);
				//this.connectSocket()
			},
			//心跳
			heart() {
				let that = this;
				clearInterval(this.timer);
				this.timer = '';
				let msg = {
					"type": "heartbeat",
				}
				this.timer = setInterval(() => {
					 that.sendSocketMessage(JSON.stringify(msg)).then(res => {
						console.log('心跳成功')
					}).catch(res => {
						console.log('发送失败')
					console.log((res))
					 })
			 
				}, 200000)
			},
			//派单播报
			dispatch(msg){
				this.innerAudioContext = wx.createInnerAudioContext();
				let that = this
				myPlugin.textToSpeech({   // 调用插件的方法
					lang: 'zh_CN',
					content:msg,
				 	success: function (res) {
				     that.playAudio(res.filename);
				 	},
				})
			},
			playAudio(e){
			     this.innerAudioContext.src = e
			     this.innerAudioContext.play();
			},	
			getnavbar(){
				this.$refs.navbar.showPage(false);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.contents{
		padding: 20rpx;
		//border-radius: 15rpx;
		//background-color: #6c6c6c;
	    //margin-top: 20px;
	}
    .button{
		margin-top: 10rpx;
	}
	.demo-layout {
	    border-radius: 4px;
		margin: 0px auto;
		margin-bottom: 10rpx;
	}
	.button view{
		font-size: 11px;
		text-align: center;
	}
	span{
		color: #6c6c6c;
		
	}
	.mapBox view{
		float: left;
	}
	.mapBoxleft{
		border:1px;
		border-style: solid ;
		border-left-color: #999999;
		height: 10px;
		margin-top: 5px;
	}
	/deep/.u-empty{
		margin-top: 100px !important;
	}
	/deep/.u-tabs__wrapper {
		display: flex;
		flex-direction: row;
		align-items: center;
		background: black;
	}
	.u_tabs {
	  position: fixed;
	 
	  //top: 10;
	  width: 100%;
	  //background-color: red;
	  height: 30px;
	  z-index: 9999;
	 
	}
	
	
</style>
